<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>食品详情</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="keywords" content="" />
    <script type="application/x-javascript">
        //scrollTo() 方法可把内容滚动到指定的坐标
        addEventListener("load",
            function() { setTimeout(hideURLbar, 0); }, false);
        function hideURLbar(){ window.scrollTo(0,1); }

    </script>


    <!-- Custom Theme files -->

    <link href="../css/app/bootstrap.css" type="text/css" rel="stylesheet" media="all">
    <link href="../css/app/style.css" type="text/css" rel="stylesheet" media="all">
    <link href="../css/fooddetail.css" type="text/css" rel="stylesheet" >
    <!-- //Custom Theme files -->
    <!-- js -->
    <script src="../js/jquery-2.2.3.min.js"></script>
    <script src="../js/axios.js">
    </script><script src="../js/vue.js"></script>
    <script src="../js/bootstrap.js"></script>
    <!-- //js -->
</head>
<body>
<div id="app"><!-- banner -->
    <div class="banner about-w3bnr">
        <!-- header -->
        <div class="header">
            <!-- //header-one -->
            <!-- navigation -->
            <div class="navigation agiletop-nav">
                <div class="container" style="margin-right: 5px;margin-left: 5px;">
                    <nav class="navbar navbar-default">
                        <!-- Brand and toggle get grouped for better mobile display -->
                        <div class="navbar-header w3l_logo">
                            <h1><a href="index.html">重生之我要做点菜系统</a></h1>
                        </div>
                        <div class="collapse navbar-collapse" id="bs-megadropdown-tabs">
                            <ul class="nav navbar-nav navbar-right">
                                <li><a href="index.html" class="active">主页</a></li>
                                <!-- Mega Menu -->
                                <li>
                                    <a href="menu.html" class="dropdown-toggle" >菜单 </a>
                                </li>
                                <li class="w3pages">
                                    <a href="orderList.html" class="dropdown-toggle">我的订单</a>
                                </li>

                                <li class="head-dpdn">
                                    <a href="login.html">登录</a>
                                </li>
                                <li class="head-dpdn">
                                    <a href="register.html">免费注册</a>
                                </li>
                                <li class="head-dpdn">
                                    <a>admin 您好！</a>
                                </li>
                                <li class="head-dpdn">
                                    <a href="../html/login.html">退出</a>
                                </li>
                            </ul>
                        </div>
                    </nav>
                </div>
            </div>
            <!-- //navigation -->
        </div>
        <!-- //header-end -->
    </div>
    <!-- //banner -->
    <!-- breadcrumb -->
    <!-- //breadcrumb -->
    <!-- products -->

    <div class="products">
        <div class="container">
            <!-- 商品详情部分 -->
            <div class="food-details">

                <div class="food-info">
                    <img :src="foods.img" alt="Food Image" class="food-image">
                    <div class="food-details">
                        <h3 id="food-name">{{foods.food_name}}</h3>
                        <p id="foods-buynum">销量:{{foods.totalbuynum}}</p>
                        <div class="discount-info" v-if="foods.discount !== 1">
                            <div class="discount-text">
                                <span class="discount-price">￥{{(foods.price * foods.discount).toFixed(2)}}</span>
                                <span><s>￥{{ (foods.price).toFixed(2) }}</s></span>
                                <span>{{foods.discount*10}}折</span>
                            </div>
                            <div class="savings-info">
                                <span class="save-label">立省</span>
                                <span class="save-amount">{{(foods.price - foods.price * foods.discount).toFixed(2)}}元</span>
                            </div>
                        </div>
                    </div>
                </div>


                <div class="food-description">
                    <div class="description-item">
                        <span>掌柜描述:</span><p>{{ details.description }}</p>
                    </div>
                    <div class="description-item">
                        <span>原料:</span><p>{{ details.ingredients }}</p>
                    </div>
                    <div class="description-item">
                        <span>凉热:</span><p>{{ details.lianre }}</p>
                    </div>
                    <div class="description-item">
                        <span>荤素:</span><p>{{ details.hunsu }}</p>
                    </div>
                    <div class="description-item">
                        <span>制作方法:</span><p>{{ details.op }}</p>
                    </div>
                    <div class="description-item">
                        <span>份量:</span><p>{{ details.weight }}</p>
                    </div>
                </div>

            </div>
            <!-- //商品详情部分 -->
            <!-- 用户评论部分 -->
            <div class="user-reviews">
                <div class=".review-container">
                    <div class="review-header">
                        <div class="total-score">{{ gettotalstar() }}分</div>
                        <div class="total-reviews">共{{ gettotalreviews() }}条评价</div>
                    </div>
                    <div class="ratings-container">
                        <div class="rating-summary">
                            <div class="rating-item">
                                <img src="../images/5星.png" class="review-star-image" alt="5星">
                                <div class="progress-bar">
                                    <div class="progress" :style="{ width: getStarPercentage(5) + '%' }"> </div>
                                </div>
                                <span class="rating-font">{{getStarPercentage(5) + '%'}}</span>
                            </div>
                        </div>
                        <div class="rating-summary">
                            <div class="rating-item">
                                <img src="../images/4星.png" class="review-star-image" alt="4星">
                                <div class="progress-bar">
                                    <div class="progress" :style="{ width: getStarPercentage(4) + '%' }"> </div>
                                </div>
                                <span class="rating-font">{{getStarPercentage(4) + '%'}}</span>
                            </div>
                        </div>
                        <div class="rating-summary">
                            <div class="rating-item">
                                <img src="../images/3星.png" class="review-star-image" alt="3星">
                                <div class="progress-bar">
                                    <div class="progress" :style="{ width: getStarPercentage(3) + '%' }"> </div>
                                </div>
                                <span class="rating-font">{{getStarPercentage(3) + '%'}}</span>
                            </div>
                        </div>
                        <div class="rating-summary">
                            <div class="rating-item">
                                <img src="../images/2星.png" class="review-star-image" alt="2星">
                                <div class="progress-bar">
                                    <div class="progress" :style="{ width: getStarPercentage(2) + '%' }"></div>
                                </div>
                                <span class="rating-font">{{getStarPercentage(2) + '%'}}</span>
                            </div>
                        </div>
                        <div class="rating-summary">
                            <div class="rating-item">
                                <img src="../images/1星.png" class="review-star-image" alt="1星">
                                <div class="progress-bar">
                                    <div class="progress" :style="{ width: getStarPercentage(1) + '%' }"></div>
                                </div>
                                <span class="rating-font">{{getStarPercentage(1) + '%'}}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <h4 class="reviews-title">用户评论</h4>
                <div class="review-filters">
                    <button @click="showAllReviews" class="rounded-button">全部</button>
                    <button @click="showGoodReviews" class="rounded-button">推荐 ({{ getsumgood() }})</button>
                    <button @click="showBadReviews" class="rounded-button">不推荐 ({{ getsumbad() }})</button>
                    <button @click="showimgReviews" class="rounded-button">带图 ({{ getsumimg() }})</button>
                </div>
<!--                评论部分-->
                <ul class="review-list">
                    <li class="review-item" v-for="(review, index) in filteredReviews" :key="index" v-show="showAll || index < 2">
                        <div class="review-content">
                            <div class="review-user">
                                <img :src="getuseravatar(review.userid)" alt="" class="user-avatar">
                                <div class="user-info">
                                    <p class="user-name">{{ getusername(review.userid) }}</p>
                                    <p class="review-date">{{ formatDate(review.createdate) }}</p>
                                </div>
                            </div>
                            <div class="review-text">
                                <img :src="'../images/' + review.star + '星.png'" alt="" class="review-star-image">
                                <p class="review-text-content">{{ review.review_text }}</p>
                                <img :src="review.review_image_url" alt="" class="review-image">
                            </div>
                        </div>
                        <!-- 展开和收起回复的按钮 -->
                        <button @click="toggleReplies(index)" class="expand-replies-btn" v-if="hasReply(review.id) && !showReplies[index]">
                            <img src="../images/展开.png" alt="展开" class="expand-icon">
                            <span>展开{{ getrepliylength(review.id) }}条回复</span>
                        </button>

                        <!-- 回复部分 -->
                        <div class="reply-item" v-for="(reply, idx) in filteredReplies(review.id)" :key="idx" v-show="showReplies[index]&& hasReply(review.id)">
                            <!-- 回复内容 -->
                            <div class="reply-content">
                                <!-- 用户信息 -->
                                <div class="reply-user">
                                    <img :src="getuseravatar(reply.user_id)" alt="" class="user-avatar">
                                    <div class="reply-info">
                                        <p class="reply-name">{{ getusername(reply.user_id) }}</p>
                                        <p class="reply-date">{{ formatDate(reply.createdate) }}</p>
                                    </div>
                                </div>
                                <!-- 回复文本 -->
                                <div class="reply-text">
                                    <p class="reply-text-content">{{ reply.reply_text }}</p>
                                    <img :src="reply.reply_image_url" alt="" class="review-image">
                                </div>
                            </div>
                        </div>

                        <!-- 收起按钮放在最下方 -->
                        <button @click="toggleReplies(index)" class="expand-replies-btn" v-if="hasReply(review.id) && showReplies[index]">
                            <img src="../images/收起.png" alt="收起" class="expand-icon">
                            <span>收起</span>
                        </button>
                    </li>
                    <li class="review-item" v-show="!showAll && reviews.length > 2" style="text-align: center;">
                        <button @click="showAllReviews" class="expand-reviews-btn">
                            <!-- 删除 style 属性，不再需要设置宽度和高度 -->
                            <img src="../images/展开.png" alt="展开" class="expand-icon">
                        </button>
                    </li>
                </ul>
            </div>




        </div>
</div>
</div>
</body>
<script >
    let app = new Vue({
        el: '#app',
        data: {
            foods: [],//食品信息
            details:[],//详情
            reviews:[],//用户评论
            users:[],//用户列表
            replies:[],//回复列表
            showReplies: [], // 用于控制每个评论的回复部分展开状态
            userid:'',//当前用户的id

            foodid:2,//食物id
            showAll: false,// 控制是否显示所有评论或部分评论
            showAllreplies:false,// 控制是否显示所有回复或部分回复
            filterType: 'all' // 过滤类型，可以是 'all', 'good', 'bad','img'
        },
        methods: {
            getrepliylength(id){
                return this.replies.filter(reply=>reply.review_id===id).length;
            },
            hasReply(id) {
                // 使用 Array.prototype.some() 方法来检查数组中是否有满足条件的元素
                return this.replies.some(reply => {return reply.review_id === id;});
            },

            toggleReplies(index) {
                // 切换评论项 index 的回复部分的展开状态
                this.$set(this.showReplies, index, !this.showReplies[index]);
            },
            fetchReplies(){
                axios.post("../fooddetail?op=getReplies")
                    .then(resp=>{
                        const jm=resp.data;
                        if (jm.code===1){
                            console.log(jm.obj);
                           this.replies=jm.obj
                        }else {
                            console.log("获取回复失败")
                        }
                    })
            },
            fetchFoods() {
                this.getfoodid();
                const params = new URLSearchParams();
                params.append("foodid", this.foodid);
                axios.post("../fooddetail?op=getfoodbyid",params)
                    .then(resp => {
                        const jm = resp.data;
                        if (jm.code===1){
                            this.foods = jm.obj;
                            console.log(this.foods);
                        }else {
                            console.log("获取食品失败")
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching foods:', error);
                    });
            },
            fetchFooddetail() {
                this.getfoodid();
                const params = new URLSearchParams();
                params.append("foodid", this.foodid);
                axios.post("../fooddetail?op=getfooddetail",params)
                    .then(resp => {
                        const jm = resp.data;
                        if (jm.code===1){
                            this.details = jm.obj;
                            console.log(this.details);
                        }else {
                            console.log("获取食品信息失败")
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching foods:', error);
                    });
            },
            fetchreview() {
                this.getfoodid();
                const params = new URLSearchParams();
                params.append("foodid", this.foodid);
                axios.post("../fooddetail?op=getreview",params)
                    .then(resp => {
                        const jm = resp.data;
                        if (jm.code===1){
                            this.reviews = jm.obj;
                            console.log(this.reviews);
                        }else {
                            console.log("获取评论失败")
                        }

                    })
                    .catch(error => {
                        console.error('Error fetching foods:', error);
                    });
            },
            fetchuser(){

                axios.post("../fooddetail?op=getuser")
                    .then(resp=>{
                    const jm=resp.data;
                    if (jm.code===1){
                        this.users=jm.obj;
                        console.log(this.users);
                    }else {
                        console.log("获取用户失败")
                    }
                })
            },
            getfoodid() {
                const foodidStr = sessionStorage.getItem("foodid");
                if (foodidStr !== null) {
                    this.foodid = parseInt(foodidStr);
                    console.log(this.foodid);
                } else {
                    // 处理用户未登录时的逻辑，例如跳转到登录页面或者设置默认值
                    this.foodid = 0; // 设置默认值为0或者其他合适的未登录状态值
                    console.log(this.foodid);
                }
            },
            getusername(userid) {

                const user = this.users.find(user => user.id === userid);
                if (user) {
                    return user.nickname;
                } else {
                    return "未知用户";
                }
            },

            getuseravatar(userid) {

                const user = this.users.find(user => user.id === userid);
                if (user) {
                    return user.avatar;
                } else {
                    return "../images/default-avatar.jpg";
                }
            },
            formatDate(dateStr) {
                const date = new Date(dateStr);
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                return `${year}.${month}.${day}`;
            },
            // 获取总评价星级
            gettotalstar() {
                if (this.reviews.length === 0) return 0;

                // 计算平均星级
                let totalStars = this.reviews.reduce((acc, review) => acc + review.star, 0);
                return (totalStars / this.reviews.length).toFixed(1);
            },
            // 获取总评价条数
            gettotalreviews() {
                return this.reviews.length;
            },
            // 获取推荐评价条数
            getsumgood() {
                return this.reviews.filter(review => review.star>=3).length;
            },
            // 获取不推荐评价条数
            getsumbad() {
                return this.reviews.filter(review => review.star<3).length;
            },
            getsumimg(){
                return this.reviews.filter(review => review.review_image_url!=="").length;
            },
            showAllReviews() {
                this.showAll = true;
                this.filterType = 'all';
            },
            showGoodReviews() {
                this.showAll = true;
                this.filterType = 'good';
            },
            showBadReviews() {
                this.showAll = true;
                this.filterType = 'bad';
            },
            showimgReviews() {
                this.showAll = true;
                this.filterType = 'img';
            },
            getStarPercentage(star){
                return ((this.reviews.filter(review => review.star===star).length/this.reviews.length)*100).toFixed(2)
            },
            getUserId() {
                const userIdStr = sessionStorage.getItem("userid");
                if (userIdStr !== null) {
                    this.userid = parseInt(userIdStr);
                } else {
                    // 处理用户未登录时的逻辑，例如跳转到登录页面或者设置默认值
                    this.userid = 0; // 设置默认值为0或者其他合适的未登录状态值
                }
            },
            filteredReplies(reviewId) {
                return this.replies.filter(reply => reply.review_id === reviewId);
            }
        },
        filters: {

        },

        computed: {
            filteredReviews() {
                if (this.filterType === 'all') {
                    return this.reviews;
                } else if (this.filterType === 'good') {
                    return this.reviews.filter(review => review.star >= 3);
                } else if (this.filterType === 'bad') {
                    return this.reviews.filter(review => review.star < 3);
                }else if (this.filterType === 'img'){
                    return this.reviews.filter(review => review.review_image_url!=="");
                }
                return [];
            },

        },
        mounted() {
            this.fetchFoods();//拿到食品信息
            this.fetchFooddetail();
            this.fetchreview();
            this.fetchuser();//拿到用户的id
            this.fetchReplies();
        }
    });
</script>
</html>